package site.edody.dframe.configuration;

import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.MagicUser;
import org.ssssssss.magicapi.core.exception.MagicLoginException;
import org.ssssssss.magicapi.core.interceptor.AuthorizationInterceptor;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;


@Component  //注入到Spring容器中
public class ScriptAuthorizationInterceptor implements AuthorizationInterceptor {

    @Autowired
    private JdbcTemplate jdbcTemplate;



    //要求登录
    @Override
    public boolean requireLogin() {
        return true;
    }

    /**
     * 根据Token获取User
     */
    @Override
    public MagicUser getUserByToken(String token) throws MagicLoginException {
//        if (判断token是否有效) {
//            return magicUser;   // 从token中获取MagicUser对象
//        }
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList("select * from api_user where token='"+token+"'");
        if (!mapList.isEmpty()){
            Map<String,Object> apiuser = (Map<String, Object>) mapList.getFirst();
            return new MagicUser(apiuser.get("id").toString(),apiuser.get("username").toString(),apiuser.get("token").toString());
        }
        throw new MagicLoginException("token无效");
    }

    @Override
    public MagicUser login(String username, String password) throws MagicLoginException {
        // 根据实际情况进行修改，如查询数据库。。
//        if("dody".equals(username) && "DFrame@222".equals(password)){
//            // 登录成功后 构造MagicUser对象。
//            return new MagicUser("1","dody","tokenvalue......");
//        }
        String dbpassword = DigestUtil.md5Hex(password);
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList("select * from api_user where username='"+username+"' and password='"+dbpassword+"'");
        if (!mapList.isEmpty()){
            Map<String,Object> apiuser = (Map<String, Object>) mapList.getFirst();
            return new MagicUser(apiuser.get("id").toString(),apiuser.get("username").toString(),apiuser.get("token").toString());
        }
        throw new MagicLoginException("用户名或密码不正确");
    }

    @Override
    public void refreshToken(MagicUser user) {
        String token = UUID.randomUUID().toString();
        jdbcTemplate.update("update api_user set token ='"+token+"' where username = "+user.getUsername());
    }
}
